<?php
	include('../session_ini.php');
	
	include_once('Querys.php');
	include_once('UsuarioService.php');
	
	class Login extends Querys{
	
		var $ip;
		var $time;
		var $session_id;
		
		/*LOGUEA CON LOS DATOS QUE LE PASO COMO ARGUMENTO*/
		
		public function loguear($usuario, $password){
			$this->ip = $_SERVER["REMOTE_ADDR"];
			$this->time = time();
			$this->session_id = session_id();
			
			$fila = $this->getAttemp($this->ip);
			
			$hora = split(" ", $fila["lastLogin"]);
			
			if($fila["attemps"] >= 3 && $this->restarHoras($hora[1], date("H:i:s", time()-(60*60))) < 30){
				//DEVUELVO 2 SI TODAVIA NO ME PUEDO LOGUEAR PORQUE ESTOY BLOQUEADO
				return 2;
			}else{
				$result = $this->consulta("SELECT * FROM usuarios WHERE usuario = '$usuario' AND password = '$password'");
				
				if($this->num_rows($result) == 1){
					$fila = $this->fetch($result);
					
					$_SESSION["id_usuario"] = $fila["id"];
					$_SESSION["usuario"] = $fila["usuario"];
					$_SESSION["nombre"] = $fila["nombre"];
					$_SESSION["email"] = $fila["email"];
					$_SESSION["imagen"] = $fila["imagen"];
					
					$_SESSION["actualizado"] = $fila["actualizado"];
					
					$this->clearAttemp($this->ip);
					
					//DEVUELVO 'true' SI ME LOGUEO CORRECTAMENTE
					return true;
					
				}else{
				
					if($this->getAttemp($this->ip) >= 0){
						$this->addAttemp($this->ip);
					}
					//DEVUELVO 1 SI AGREGO UN INTENTO DE LOGIN
					return 1;
					
				}
			}
		}
		
		private function setIp($ip){
			if($this->consulta("INSERT INTO login_attemps(ip, attemps, lastLogin) VALUES ('".$ip."', 0, NOW())")){
				return true;
			}
		}
		
		private function getAttemp($ip){
			$result = $this->consulta("SELECT * FROM login_attemps WHERE ip = '".$ip."'");
			if($this->num_rows($result) > 0){
				$fila = $this->fetch($result);
				return $fila;
			}else{
				$this->setIp($this->ip);
				
				return 0;
			}
		}
		
		private function addAttemp($ip){
			if($this->consulta("UPDATE login_attemps SET attemps = attemps+1 WHERE ip = '".$ip."'")){
				return true;
			}
		}
		
		private function clearAttemp($ip){
			if($this->consulta("DELETE FROM login_attemps WHERE ip = '".$ip."'")){
				return true;
			}
		}
		
		/*TERMINAR NO FUNCIONA*/
		
		private function restarHoras($hora1,$hora2){
			$separar[1]=explode(':',$hora1);
			$separar[2]=explode(':',$hora2);

			$total_minutos_trasncurridos[1] = ($separar[1][0]*60)+$separar[1][1];
			$total_minutos_trasncurridos[2] = ($separar[2][0]*60)+$separar[2][1];
			$total_minutos_trasncurridos = intval($total_minutos_trasncurridos[2])-intval($total_minutos_trasncurridos[1]);
				
			return $total_minutos_trasncurridos;

		} 
	}
?>